package com.own.demo.jts;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.own.demo.utils.CommWriterFileInfo;
import com.own.demo.utils.DateUtils;
import com.own.demo.utils.FileToStringUtils;
import com.own.demo.vo.Bounds;
import com.own.demo.vo.NodeOsmInfo;


import java.io.BufferedWriter;
import java.io.File;
import java.text.ParseException;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

public class Main2 {
    private  static BufferedWriter bufferedWriter = CommWriterFileInfo.getWriterBuffer("E:\\ownCode\\UMA\\数据\\路网数据\\base" + "\\" + "changsha-"+ DateUtils.getHHMMSS()+".osm", false);
    private static AtomicLong indexNum = new AtomicLong(1);
    private static Map<String, NodeOsmInfo> lonLatMap;

    public static void main(String[] args) throws ParseException {
        //head
        writerHeader();
        //边界
        Bounds boundingBox = new Bounds(114.260085, 114.260085, 27.848061, 28.661844);
        setBounds(boundingBox);
        try{
            File geoZJ = new File("E:\\ownCode\\UMA\\数据\\路网数据\\base\\长沙市1-base-20231126144250.geojson");
            String geoData = FileToStringUtils.txt2String(geoZJ);
            JSONObject jsonObject=JSONObject.parseObject(geoData);
            geoData="";
            getJsonNode(jsonObject);
            writerNode();
            writerWay(jsonObject);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            endString();
        }

    }

    public static void writerWay(JSONObject jsonObject){
        JSONArray jsonArray = jsonObject.getJSONArray("features");
        int row = jsonArray.size();
        for (int i = 0; i < row; i++) {
            StringBuilder sb=new StringBuilder(1024);
            String id=indexNum.getAndIncrement()+"";
            sb.append("   <way id=\""+id+"\" visible=\"true\" version=\"1\"> \r\n");

            JSONObject indexJsonObje = jsonArray.getJSONObject(i);
            JSONObject geometry = indexJsonObje.getJSONObject("geometry");
            JSONArray lonlatList = geometry.getJSONArray("coordinates");
            JSONObject properties=jsonObject.getJSONObject("properties");

            int index=lonlatList.size();
            for (int j = 0; j < index; j++) {
                JSONArray point = lonlatList.getJSONArray(j);
                double lon = point.getDouble(0);
                double lat = point.getDouble(1);
                String key = lon + "+" + lat;
                NodeOsmInfo nodeInfo=lonLatMap.get(key);
                sb.append("      <nd ref=\""+nodeInfo.getIndex()+"\"/> \r\n");
            }

            if(properties !=null) {
                Set<String> keys = properties.keySet();
                Iterator<String> iterator = keys.iterator();
                while(iterator.hasNext()){
                    String key = iterator.next();
                    String o =properties.getString(key);
                    String tags="      <tag k=\""+key+"\" v=\""+o+"\"/> \r\n";
                    sb.append(tags);
                }
            }

            String key="name";
            String value=id+"-"+i;
            String tags="      <tag k=\""+key+"\" v=\""+value+"\"/> \r\n";
            sb.append(tags);

            sb.append("      <tag k=\"highway\" v=\"motorway\"/> \r\n");
            sb.append("   </way> \r\n");
            String wayStr=sb.toString();
            CommWriterFileInfo.writer(bufferedWriter, wayStr);
            System.out.println("Way: "+DateUtils.getDateYYSs(new Date())+" "+wayStr);
        }
    }

    public static void getJsonNode(JSONObject geoJson) {
        JSONArray jsonArray = geoJson.getJSONArray("features");
        int row = jsonArray.size();
        lonLatMap = new ConcurrentHashMap<>(row);
        for (int i = 0; i < row; i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            JSONObject properties = jsonObject.getJSONObject("properties");
            String propKey = "name";
            JSONObject geometry = jsonObject.getJSONObject("geometry");
            JSONArray lonlatList = geometry.getJSONArray("coordinates");
            int lonlatSize = lonlatList.size();
            for (int j = 0; j < lonlatSize; j++) {
                JSONArray point = lonlatList.getJSONArray(j);
                double lon = point.getDouble(0);
                double lat = point.getDouble(1);
                String key = lon + "+" + lat;
                String index=indexNum.getAndIncrement()+"";
                System.out.println("写入node: "+DateUtils.getDateYYSs(new Date())+" key:"+index+"  xy:"+key);
                lonLatMap.put(key, new NodeOsmInfo(properties.getString(propKey), index, propKey, lon, lat));
            }
        }
    }


    public static void writerNode() {
        for (Map.Entry<String, NodeOsmInfo> node : lonLatMap.entrySet()) {
            NodeOsmInfo nodeInfo=node.getValue();
            double lon=nodeInfo.getX();
            double lat=nodeInfo.getY();
            String nodeStr="<node id=\""+nodeInfo.getIndex()+"\" visible=\"true\" version=\"1\" lat=\""+lat+"\" lon=\""+lon+"\"/>";
            CommWriterFileInfo.writer(bufferedWriter, nodeStr);
            System.out.println("写入node: "+nodeStr);
        }
    }



    private static void setBounds(Bounds boundingBox){
        double minLat=boundingBox.getMinLat();
        double maxLat=boundingBox.getMaxLat();
        double minLon=boundingBox.getMinLon();
        double maxLong=boundingBox.getMaxLon();
        long index=indexNum.getAndIncrement();
        String bounds="<bounds minlat=\""+minLat+"\" minlon=\""+minLon+"\" maxlat=\""+maxLat+"\" maxlon=\""+maxLong+"\" id=\"1\" version=\""+index+"\"/>";
        CommWriterFileInfo.writer(bufferedWriter, bounds);
    }
    private static void writerHeader(){
        String head="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<osm version=\"0.6\" generator=\"CGImap 0.8.8 (587855 spike-08.openstreetmap.org)\" copyright=\"OpenStreetMap and contributors\" attribution=\"http://www.openstreetmap.org/copyright\" license=\"http://opendatacommons.org/licenses/odbl/1-0/\">";
        CommWriterFileInfo.writer(bufferedWriter, head);
    }

    private static void endString(){
        CommWriterFileInfo.writer(bufferedWriter, "</osm>");
    }
}
